'''
Created on Nov 29, 2010

@author: dexen
'''

import sys
import traceback

import dexen

import conds
from individual import Individual
from const import POP_SIZE, MAX_BIRTHS, FEED_SIZE
from slave_tasks.dev import DevTask
from slave_tasks.eval import EvalATask, EvalBTask
from slave_tasks.feedback import FeedbackTask



class MasterTask(dexen.BaseMasterTask):
    def __init__(self, master_env):
        try:
            print "I am initializing in mastertask"
            assert isinstance(master_env, dexen.MasterEnv)
            master_env.start_task(DevTask, "Dev", 1, conds.dev_cond)
            master_env.start_task(EvalATask, "EvalA", 1, conds.evalA_cond)
            master_env.start_task(EvalBTask, "EvalB", 1, conds.evalB_cond)
            master_env.start_task(FeedbackTask, "Feedback", FEED_SIZE, conds.feedback_cond)
            print "I have started all the tasks"
        except:
            print "MasterTask: Exception"
            traceback.print_tb(sys.exc_info()[2])
        for _ in range(POP_SIZE):
            ind = Individual()
            #print "MasterTask: ", ind
            master_env.set_ind(ind)
        self.last_size = POP_SIZE
        self.cnt = 1
        
    def __execute__(self, master_env):
        print "I am executing master task"
        assert isinstance(master_env, dexen.MasterEnv)
        pop_size = master_env.num_inds()
        print "MasterTask: pop size is ", pop_size

        if self.cnt == 5:
            master_env.archive_to_file("test.txt", "Master Task: Hello World")
            master_env.set_slave_data("ga", 101)

        if pop_size == MAX_BIRTHS:
            master_env.stop_master()
        
        self.last_size = pop_size
        self.cnt += 1
    
            